<template>
  <div class="create-container">
    <h2 class="page-title">
      <i class="fas fa-pen-fancy" style="color: #42b983; margin-right: 10px;"></i>
      提交个人简历
    </h2>

    <!-- 表单卡片 -->
    <div class="form-card">
      <!-- 基本信息区域 -->
      <div class="form-section">
        <h3 class="section-title">一、基本信息</h3>
        <div class="form-grid">
          <div class="form-item">
            <label class="form-label required">姓名</label>
            <input
                v-model="formData.name"
                type="text"
                class="form-input"
                placeholder="请输入您的姓名"
            />
          </div>
          <div class="form-item">
            <label class="form-label required">应届年份</label>
            <input
                v-model="formData.graduate_year"
                type="text"
                class="form-input"
                placeholder="如：24年应届生、2025届"
            />
          </div>
          <div class="form-item">
            <label class="form-label required">学历</label>
            <select v-model="formData.education" class="form-select">
              <option value="">请选择学历</option>
              <option value="大专">大专</option>
              <option value="本科">本科</option>
              <option value="硕士">硕士</option>
              <option value="博士">博士</option>
              <option value="其他">其他</option>
            </select>
          </div>
          <div class="form-item">
            <label class="form-label">求职状态</label>
            <input
                v-model="formData.job_status"
                type="text"
                class="form-input"
                placeholder="如：在校-考虑机会、离职-随时到岗"
            />
          </div>
          <div class="form-item">
            <label class="form-label required">手机号</label>
            <input
                v-model="formData.phone"
                type="tel"
                class="form-input"
                placeholder="请输入11位有效手机号"
            />
          </div>
          <div class="form-item">
            <label class="form-label">简历评分</label>
            <input
                v-model="formData.resume_score"
                type="number"
                class="form-input"
                min="0"
                max="100"
                placeholder="0-100分（默认0）"
            />
          </div>
          <div class="form-item">
            <label class="form-label">待优化项数量</label>
            <input
                v-model="formData.optimization_items"
                type="number"
                class="form-input"
                min="0"
                placeholder="如：2（默认0）"
            />
          </div>
          <div class="form-item">
            <label class="form-label">个人优势</label>
            <input
                v-model="formData.preponderance"
                type="text"
                class="form-input"
                placeholder="如：Python熟练、有项目经验"
            />
          </div>
          <div class="form-item">
            <label class="form-label required">期望职位</label>
            <input
                v-model="formData.expectedJob"
                type="text"
                class="form-input"
                placeholder="如：后端开发工程师、前端开发"
            />
          </div>
        </div>
      </div>

      <!-- 工作/实习经历区域 -->
      <div class="form-section">
        <div class="section-header">
          <h3 class="section-title">二、工作/实习经历</h3>
          <button
              @click="addWorkExperience()"
              class="btn btn-primary btn-sm"
          >
            <i class="fas fa-plus" style="margin-right: 5px;"></i>
            添加经历
          </button>
        </div>
        <div class="experience-list">
          <div
              v-for="(item, index) in formData.work_experiences"
              :key="index"
              class="experience-item"
          >
            <div class="experience-header">
              <span class="experience-index">经历 {{ index + 1 }}</span>
              <button
                  @click="removeWorkExperience(index)"
                  class="btn btn-danger btn-sm"
              >
                <i class="fas fa-trash"></i>
              </button>
            </div>
            <div class="experience-form">
              <div class="form-grid">
                <div class="form-item">
                  <label class="form-label required">公司名称</label>
                  <input
                      v-model="item.company"
                      type="text"
                      class="form-input"
                      placeholder="请输入公司名称"
                  />
                </div>
                <div class="form-item">
                  <label class="form-label required">职位</label>
                  <input
                      v-model="item.position"
                      type="text"
                      class="form-input"
                      placeholder="请输入您的职位"
                  />
                </div>
                <div class="form-item">
                  <label class="form-label required">开始日期</label>
                  <input
                      v-model="item.start_date"
                      type="date"
                      class="form-input"
                  />
                </div>
                <div class="form-item">
                  <label class="form-label">结束日期</label>
                  <input
                      v-model="item.end_date"
                      type="date"
                      class="form-input"
                      placeholder="未结束可不填"
                  />
                </div>
                <div class="form-item form-item-full">
                  <label class="form-label required">工作描述</label>
                  <textarea
                      v-model="item.description"
                      class="form-textarea"
                      rows="3"
                      placeholder="请描述您的工作内容、职责和成果（如：负责XX功能开发，提升效率XX%）"
                  ></textarea>
                </div>
              </div>
            </div>
          </div>
          <div v-if="formData.work_experiences.length === 0" class="empty-tip">
            暂无工作/实习经历，点击"添加经历"按钮添加
          </div>
        </div>
      </div>

      <!-- 项目经历区域 -->
      <div class="form-section">
        <div class="section-header">
          <h3 class="section-title">三、项目经历</h3>
          <button
              @click="addProjectExperience()"
              class="btn btn-primary btn-sm"
          >
            <i class="fas fa-plus" style="margin-right: 5px;"></i>
            添加项目
          </button>
        </div>
        <div class="experience-list">
          <div
              v-for="(item, index) in formData.project_experiences"
              :key="index"
              class="experience-item"
          >
            <div class="experience-header">
              <span class="experience-index">项目 {{ index + 1 }}</span>
              <button
                  @click="removeProjectExperience(index)"
                  class="btn btn-danger btn-sm"
              >
                <i class="fas fa-trash"></i>
              </button>
            </div>
            <div class="experience-form">
              <div class="form-grid">
                <div class="form-item">
                  <label class="form-label required">项目名称</label>
                  <input
                      v-model="item.project_name"
                      type="text"
                      class="form-input"
                      placeholder="请输入项目名称"
                  />
                </div>
                <div class="form-item">
                  <label class="form-label required">项目角色</label>
                  <input
                      v-model="item.role"
                      type="text"
                      class="form-input"
                      placeholder="如：开发工程师、项目负责人"
                  />
                </div>
                <div class="form-item">
                  <label class="form-label required">开始日期</label>
                  <input
                      v-model="item.start_date"
                      type="date"
                      class="form-input"
                  />
                </div>
                <div class="form-item">
                  <label class="form-label">结束日期</label>
                  <input
                      v-model="item.end_date"
                      type="date"
                      class="form-input"
                      placeholder="未结束可不填"
                  />
                </div>
                <div class="form-item form-item-full">
                  <label class="form-label required">项目描述</label>
                  <textarea
                      v-model="item.description"
                      class="form-textarea"
                      rows="3"
                      placeholder="请描述项目背景、您的职责、使用的技术栈和项目成果"
                  ></textarea>
                </div>
              </div>
            </div>
          </div>
          <div v-if="formData.project_experiences.length === 0" class="empty-tip">
            暂无项目经历，点击"添加项目"按钮添加
          </div>
        </div>
      </div>

      <!-- 教育经历区域 -->
      <div class="form-section">
        <div class="section-header">
          <h3 class="section-title">四、教育经历</h3>
          <button
              @click="addEducationExperience()"
              class="btn btn-primary btn-sm"
          >
            <i class="fas fa-plus" style="margin-right: 5px;"></i>
            添加教育经历
          </button>
        </div>
        <div class="experience-list">
          <div
              v-for="(item, index) in formData.education_experiences"
              :key="index"
              class="experience-item"
          >
            <div class="experience-header">
              <span class="experience-index">教育经历 {{ index + 1 }}</span>
              <button
                  @click="removeEducationExperience(index)"
                  class="btn btn-danger btn-sm"
              >
                <i class="fas fa-trash"></i>
              </button>
            </div>
            <div class="experience-form">
              <div class="form-grid">
                <div class="form-item">
                  <label class="form-label required">学校名称</label>
                  <input
                      v-model="item.school"
                      type="text"
                      class="form-input"
                      placeholder="请输入学校名称"
                  />
                </div>
                <div class="form-item">
                  <label class="form-label required">学历</label>
                  <select v-model="item.education" class="form-select">
                    <option value="">请选择学历</option>
                    <option value="大专">大专</option>
                    <option value="本科">本科</option>
                    <option value="硕士">硕士</option>
                    <option value="博士">博士</option>
                  </select>
                </div>
                <div class="form-item">
                  <label class="form-label">专业</label>
                  <input
                      v-model="item.major"
                      type="text"
                      class="form-input"
                      placeholder="请输入您的专业"
                  />
                </div>
                <div class="form-item">
                  <label class="form-label required">入学日期</label>
                  <input
                      v-model="item.start_date"
                      type="date"
                      class="form-input"
                  />
                </div>
                <div class="form-item">
                  <label class="form-label required">毕业日期</label>
                  <input
                      v-model="item.end_date"
                      type="date"
                      class="form-input"
                  />
                </div>
                <div class="form-item form-item-full">
                  <label class="form-label">补充描述</label>
                  <textarea
                      v-model="item.description"
                      class="form-textarea"
                      rows="2"
                      placeholder="如：获奖情况、担任职务、主修课程等"
                  ></textarea>
                </div>
              </div>
            </div>
          </div>
          <div v-if="formData.education_experiences.length === 0" class="empty-tip">
            暂无教育经历，点击"添加教育经历"按钮添加
          </div>
        </div>
      </div>

      <!-- 提交按钮区域 -->
      <div class="form-submit">
        <button
            @click="submitResume()"
            class="btn btn-primary btn-lg"
            :disabled="isSubmitting"
        >
          <i
              v-if="isSubmitting"
              class="fas fa-spinner fa-spin"
              style="margin-right: 5px;"
          ></i>
          {{ isSubmitting ? "提交中..." : "提交简历" }}
        </button>
      </div>

      <!-- 提交结果提示 -->
      <div
          v-if="message"
          :class="['message-box', messageType === 'success' ? 'success' : 'error']"
      >
        <i
            :class="
            messageType === 'success'
              ? 'fas fa-check-circle'
              : 'fas fa-exclamation-circle'
          "
            style="margin-right: 5px;"
        ></i>
        {{ message }}
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import { useRouter } from 'vue-router';
import axios from 'axios';

const router = useRouter();

// 表单数据（与后端接口字段完全对应）
const formData = ref({
  name: '',
  graduate_year: '',
  education: '',
  job_status: '',
  phone: '',
  resume_score: 0,
  optimization_items: 0,
  preponderance: '',
  expectedJob: '',
  work_experiences: [], // 工作经历列表
  project_experiences: [], // 项目经历列表
  education_experiences: [] // 教育经历列表
});

// 状态变量
const isSubmitting = ref(false); // 提交中状态
const message = ref(''); // 提示信息
const messageType = ref(''); // 提示类型（success/error）

// 添加工作经历
const addWorkExperience = () => {
  formData.value.work_experiences.push({
    company: '',
    position: '',
    start_date: '',
    end_date: '',
    description: ''
  });
};

// 删除工作经历
const removeWorkExperience = (index) => {
  formData.value.work_experiences.splice(index, 1);
};

// 添加项目经历
const addProjectExperience = () => {
  formData.value.project_experiences.push({
    project_name: '',
    role: '',
    start_date: '',
    end_date: '',
    description: ''
  });
};

// 删除项目经历
const removeProjectExperience = (index) => {
  formData.value.project_experiences.splice(index, 1);
};

// 添加教育经历
const addEducationExperience = () => {
  formData.value.education_experiences.push({
    school: '',
    education: '',
    major: '',
    start_date: '',
    end_date: '',
    description: ''
  });
};

// 删除教育经历
const removeEducationExperience = (index) => {
  formData.value.education_experiences.splice(index, 1);
};

// 显示提示信息
const showMessage = (text, type) => {
  message.value = text;
  messageType.value = type;
  // 5秒后自动隐藏提示
  setTimeout(() => {
    message.value = '';
  }, 5000);
};

// 提交简历核心逻辑
const submitResume = async () => {
  // 1. 表单基础校验（前端预校验，减少无效请求）
  if (!formData.value.name.trim()) {
    showMessage('请输入姓名', 'error');
    return;
  }
  if (!formData.value.graduate_year.trim()) {
    showMessage('请输入应届年份', 'error');
    return;
  }
  if (!formData.value.education) {
    showMessage('请选择学历', 'error');
    return;
  }
  if (!formData.value.phone.trim() || !/^1[3-9]\d{9}$/.test(formData.value.phone)) {
    showMessage('请输入11位有效手机号', 'error');
    return;
  }
  if (!formData.value.expectedJob.trim()) {
    showMessage('请输入期望职位', 'error');
    return;
  }

  // 2. 验证关联经历（如果有经历，校验必填字段）
  const validateExperiences = () => {
    // 验证工作经历
    for (let i = 0; i < formData.value.work_experiences.length; i++) {
      const item = formData.value.work_experiences[i];
      if (!item.company.trim()) {
        showMessage(`工作经历${i+1}：请输入公司名称`, 'error');
        return false;
      }
      if (!item.position.trim()) {
        showMessage(`工作经历${i+1}：请输入职位`, 'error');
        return false;
      }
      if (!item.start_date) {
        showMessage(`工作经历${i+1}：请选择开始日期`, 'error');
        return false;
      }
      if (!item.description.trim()) {
        showMessage(`工作经历${i+1}：请输入工作描述`, 'error');
        return false;
      }
      if (item.end_date && new Date(item.end_date) < new Date(item.start_date)) {
        showMessage(`工作经历${i+1}：结束日期不能早于开始日期`, 'error');
        return false;
      }
    }

    // 验证项目经历
    for (let i = 0; i < formData.value.project_experiences.length; i++) {
      const item = formData.value.project_experiences[i];
      if (!item.project_name.trim()) {
        showMessage(`项目经历${i+1}：请输入项目名称`, 'error');
        return false;
      }
      if (!item.role.trim()) {
        showMessage(`项目经历${i+1}：请输入项目角色`, 'error');
        return false;
      }
      if (!item.start_date) {
        showMessage(`项目经历${i+1}：请选择开始日期`, 'error');
        return false;
      }
      if (!item.description.trim()) {
        showMessage(`项目经历${i+1}：请输入项目描述`, 'error');
        return false;
      }
      if (item.end_date && new Date(item.end_date) < new Date(item.start_date)) {
        showMessage(`项目经历${i+1}：结束日期不能早于开始日期`, 'error');
        return false;
      }
    }

    // 验证教育经历
    for (let i = 0; i < formData.value.education_experiences.length; i++) {
      const item = formData.value.education_experiences[i];
      if (!item.school.trim()) {
        showMessage(`教育经历${i+1}：请输入学校名称`, 'error');
        return false;
      }
      if (!item.education) {
        showMessage(`教育经历${i+1}：请选择学历`, 'error');
        return false;
      }
      if (!item.start_date) {
        showMessage(`教育经历${i+1}：请选择入学日期`, 'error');
        return false;
      }
      if (!item.end_date) {
        showMessage(`教育经历${i+1}：请选择毕业日期`, 'error');
        return false;
      }
      if (new Date(item.end_date) < new Date(item.start_date)) {
        showMessage(`教育经历${i+1}：毕业日期不能早于入学日期`, 'error');
        return false;
      }
    }
    return true;
  };

  if (!validateExperiences()) {
    return;
  }

  // 3. 开始提交
  isSubmitting.value = true;
  message.value = '';

  try {
    // 4. 调用后端创建接口
    // 后端路由：path('resume/', include('resume.urls'))，所以完整路径是 http://127.0.0.1:8000/resume/resumes/create/
    const response = await axios.post('http://127.0.0.1:8000/resume/resumes/create/', formData.value, {
      headers: {
        'Content-Type': 'application/json'
      }
    });

    // 5. 提交成功
    showMessage(
        `简历提交成功！您的简历ID为：${response.data.id || '未知'}，3秒后跳转到列表页`,
        'success'
    );

    // 6. 3秒后跳转到简历列表页
    setTimeout(() => {
      router.push('/resume');
    }, 3000);

  } catch (error) {
    // 7. 提交失败（处理后端返回的错误信息）
    isSubmitting.value = false;
    console.error('提交简历失败:', error);
    
    let errorMessage = '提交失败：';
    
    if (error.response) {
      const status = error.response.status;
      const data = error.response.data;
      
      if (status === 404) {
        errorMessage += '接口不存在，请检查后端路由配置';
      } else if (status === 400) {
        // 400 错误通常是验证失败
        if (typeof data === 'object' && data !== null) {
          // 优先使用后端格式化的错误信息
          if (data.details && Array.isArray(data.details)) {
            errorMessage += data.details.join('；');
          } else if (data.error) {
            // 如果有 error 字段，使用它
            errorMessage += data.error;
            if (data.details && Array.isArray(data.details)) {
              errorMessage += '：' + data.details.join('；');
            } else if (data.message) {
              errorMessage += '：' + data.message;
            }
          } else {
            // 处理 DRF 原始错误格式（兼容旧版本）
            errorMessage += parseDRFErrors(data);
          }
        } else if (typeof data === 'string') {
          errorMessage += data;
        } else {
          errorMessage += '数据验证失败，请检查表单填写是否正确';
        }
      } else if (status === 500) {
        errorMessage += data?.error || data?.message || '服务器内部错误，请稍后重试';
      } else {
        errorMessage += `服务器错误（${status}）`;
      }
    } else if (error.message) {
      if (error.message.includes('Network Error') || error.message.includes('ERR_CONNECTION_REFUSED')) {
        errorMessage += '无法连接到服务器，请检查后端是否启动（http://127.0.0.1:8000）';
      } else {
        errorMessage += error.message;
      }
    } else {
      errorMessage += '未知错误，请稍后重试';
    }
    
    showMessage(errorMessage, 'error');
  }
  
  // 解析 DRF 错误格式的辅助函数
  function parseDRFErrors(errors) {
    const errorMessages = [];
    
    for (const key in errors) {
      const value = errors[key];
      
      // 处理嵌套序列化器的错误（如 work_experiences, education_experiences）
      if (key === 'work_experiences' || key === 'education_experiences' || key === 'project_experiences') {
        if (Array.isArray(value)) {
          // 遍历每条经历的错误
          value.forEach((itemErrors, index) => {
            if (typeof itemErrors === 'object' && itemErrors !== null) {
              // 每条经历可能有多个字段错误
              const itemErrorMsgs = [];
              for (const errorField in itemErrors) {
                const errorMsgs = itemErrors[errorField];
                if (Array.isArray(errorMsgs)) {
                  itemErrorMsgs.push(`${errorField}: ${errorMsgs.join(', ')}`);
                } else {
                  itemErrorMsgs.push(`${errorField}: ${errorMsgs}`);
                }
              }
              if (itemErrorMsgs.length > 0) {
                errorMessages.push(`${key}[${index + 1}]: ${itemErrorMsgs.join('; ')}`);
              }
            } else if (Array.isArray(itemErrors)) {
              errorMessages.push(`${key}[${index + 1}]: ${itemErrors.join(', ')}`);
            }
          });
        } else if (typeof value === 'object') {
          // 如果是字典格式的错误
          for (const errorKey in value) {
            errorMessages.push(`${key}.${errorKey}: ${value[errorKey]}`);
          }
        } else {
          errorMessages.push(`${key}: ${value}`);
        }
      } else {
        // 处理普通字段的错误
        if (Array.isArray(value)) {
          errorMessages.push(`${key}: ${value.join('、')}`);
        } else if (typeof value === 'object' && value !== null) {
          // 嵌套的错误对象
          for (const nestedKey in value) {
            const nestedValue = value[nestedKey];
            if (Array.isArray(nestedValue)) {
              errorMessages.push(`${key}.${nestedKey}: ${nestedValue.join('、')}`);
            } else {
              errorMessages.push(`${key}.${nestedKey}: ${nestedValue}`);
            }
          }
        } else {
          errorMessages.push(`${key}: ${value}`);
        }
      }
    }
    
    return errorMessages.length > 0 ? errorMessages.join('；') : '数据验证失败';
  }
};
</script>

<style scoped>
/* 页面容器样式 */
.create-container {
  width: 100%;
}

.page-title {
  color: #333;
  font-size: 22px;
  margin-bottom: 20px;
  font-weight: 600;
}

/* 表单卡片样式 */
.form-card {
  background-color: #ffffff;
  border-radius: 12px;
  box-shadow: 0 2px 15px rgba(0, 0, 0, 0.05);
  padding: 30px;
}

/* 表单区域样式 */
.form-section {
  margin-bottom: 30px;
  padding-bottom: 20px;
  border-bottom: 1px solid #f0f0f0;
}

.form-section:last-child {
  border-bottom: none;
  margin-bottom: 20px;
  padding-bottom: 0;
}

.section-title {
  color: #333;
  font-size: 18px;
  margin-bottom: 20px;
  font-weight: 600;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

/* 表单网格布局 */
.form-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
}

.form-item {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.form-item-full {
  grid-column: 1 / -1; /* 占满整行 */
}

.form-label {
  color: #666;
  font-size: 14px;
  font-weight: 500;
}

.form-label.required::after {
  content: '*';
  color: #ff4d4f;
  margin-left: 4px;
}

.form-input,
.form-select,
.form-textarea {
  padding: 10px 12px;
  border: 1px solid #e0e0e0;
  border-radius: 6px;
  font-size: 14px;
  transition: border-color 0.3s ease;
}

.form-input:focus,
.form-select:focus,
.form-textarea:focus {
  outline: none;
  border-color: #42b983;
  box-shadow: 0 0 0 2px rgba(66, 185, 131, 0.1);
}

.form-textarea {
  resize: vertical;
}

/* 经历列表样式 */
.experience-list {
  margin-top: 10px;
}

.experience-item {
  background-color: #fafafa;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 15px;
}

.experience-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.experience-index {
  font-weight: 600;
  color: #333;
  font-size: 15px;
}

.experience-form {
  margin-top: 15px;
}

.empty-tip {
  color: #999;
  text-align: center;
  padding: 20px;
  font-size: 14px;
}

/* 按钮样式 */
.btn {
  padding: 8px 16px;
  border-radius: 6px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
  border: none;
  display: inline-flex;
  align-items: center;
  justify-content: center;
}

.btn-primary {
  background-color: #42b983;
  color: #ffffff;
}

.btn-primary:hover {
  background-color: #359469;
}

.btn-primary:disabled {
  background-color: #8dd5b5;
  cursor: not-allowed;
}

.btn-danger {
  background-color: #ff4d4f;
  color: #ffffff;
}

.btn-danger:hover {
  background-color: #d9363e;
}

.btn-sm {
  padding: 4px 10px;
  font-size: 13px;
}

.btn-lg {
  padding: 12px 24px;
  font-size: 16px;
}

/* 提交按钮区域 */
.form-submit {
  margin-top: 30px;
  text-align: center;
}

/* 提示信息样式 */
.message-box {
  margin-top: 20px;
  padding: 12px 16px;
  border-radius: 6px;
  font-size: 14px;
  display: flex;
  align-items: center;
}

.message-box.success {
  background-color: #f0f9f4;
  color: #359469;
  border: 1px solid #c3e6d5;
}

.message-box.error {
  background-color: #fff2f0;
  color: #d9363e;
  border: 1px solid #ffccc7;
}
</style>